import axios from "axios";
import React, { useEffect, useState } from "react";
import { Swiper } from "react-vant";
import { NavLink } from "react-router-dom";
export interface ListRawState {
  image: string;
  id: string;
  title: string;
  desc: string;
  price: number;
}

const Index: React.FC = () => {
  // 1. 数据容器
  const [banners, setBanners] = useState<string[]>([]);
  const [list, setList] = useState<ListRawState[]>([]);

  // 2. 请求函数
  const fetchBanners = async () => {
    const resp = await axios.get("/api/banners");
    setBanners(resp.data.data);
  };

  const fetchList = async () => {
    const resp = await axios.get("/api/lists");
    setList(resp.data.data);
  };

  // 3. 副作用函数
  useEffect(() => {
    fetchBanners();
    fetchList();
  }, []);

  return (
    <div>
      {banners.length && (
        <Swiper autoplay={5000}>
          {banners.map((v, i) => {
            return (
              <Swiper.Item key={i}>
                <img src={v} alt="" width={"100%"} />
              </Swiper.Item>
            );
          })}
        </Swiper>
      )}
      <div className="list">
        {list.map((v, i) => {
          return (
            <NavLink
              to={`/detail/${v.id}`}
              // 路由隐式传参
              state={v}
              key={i}
            >
              <div className="list-item" key={i}>
                <img src={v.image} alt="" />
                <div className="right">
                  <div className="title">{v.title}</div>
                  <div className="desc">{v.desc}</div>
                  <div className="price">{v.price}</div>
                </div>
              </div>
            </NavLink>
          );
        })}
      </div>
    </div>
  );
};

export default Index;
